package org.xlp.base.application.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xlp.utils.XLPCharsetUtil;
import org.xlp.utils.io.XLPIOUtil;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.Reader;
import java.util.Properties;

/**
 * Create by xlp on 2022/7/25
 *
 * Properties 配置文件读取工具类
 */
public class PropertiesFileReaderUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(PropertiesFileReaderUtils.class);

    /**
     * 读取配置文件类容
     *
     * @param fileName 文件名称，相对于classes路径
     * @return Properties对象
     */
    public static Properties loadFromRelativePath(String fileName){
        InputStream inputStream = null;
        Properties properties = new Properties();
        try {
            inputStream = PropertiesFileReaderUtils.class.getClassLoader()
                    .getResourceAsStream(fileName);
            return load(inputStream);
        } catch (Throwable e) {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error("加载配置文件" + fileName + " 失败！", e);
            }
        } finally {
            XLPIOUtil.closeInputStream(inputStream);
        }
        return properties;
    }

    /**
     * 读取配置文件类容
     *
     * @param fileName 文件名称，绝对路径
     * @return Properties对象
     */
    public static Properties loadFromAbsolutePath(String fileName){
        InputStream inputStream = null;
        Properties properties = new Properties();
        try {
            inputStream = new FileInputStream(fileName);
            return load(inputStream);
        } catch (Throwable e) {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error("加载配置文件" + fileName + " 失败！", e);
            }
        } finally {
            XLPIOUtil.closeInputStream(inputStream);
        }
        return properties;
    }

    /**
     * 读取配置文件类容，输入流已被关闭，无需在关闭
     *
     * @param inputStream Properties配置文件的输入流
     * @return 假如输入流为null，则返回一个空的Properties
     */
    public static Properties load(InputStream inputStream){
        Properties properties = new Properties();
        //假如输入流为null 直接返回一个空的Properties
        if (inputStream == null) return properties;

        Reader reader = null;
        try {
            byte[] bytes = XLPIOUtil.IOToByteArray(inputStream, false);
            InputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
            //获取文件编码
            String charsetName = XLPCharsetUtil.gainCharsetName(bytes);

            //处理中文乱码问题
            reader = XLPIOUtil.getReader(byteArrayInputStream, charsetName);
            properties.load(reader);
        } catch (Throwable e) {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error("读取配置文件失败！", e);
            }
        } finally {
            XLPIOUtil.closeInputStream(inputStream);
            XLPIOUtil.closeReader(reader);
        }
        return properties;
    }
}
